<template>
    <div class="carousel-management">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>轮播图管理</h2>
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>新增轮播图
        </el-button>
      </div>
  
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索轮播图标题"
          class="search-input"
          clearable
          @keyup.enter="fetchCarousels"
          @clear="fetchCarousels"
        >
          <template #append>
            <el-button @click="fetchCarousels">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
  
      <!-- 轮播图列表 -->
      <el-table
        :data="pagedData"
        border
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="图片" width="180" align="center">
          <template #default="{row}">
            <el-image
              style="width: 150px; height: 100px"
              :src="row.img"
              :preview-src-list="[row.img]"
              fit="cover"
              preview-teleported
              hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{row}">
            <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="filteredCarousels.length"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
  
      <!-- 新增/编辑轮播图对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑轮播图' : '新增轮播图'"
        width="50%"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入轮播图标题" />
          </el-form-item>
          
          <el-form-item label="图片URL" prop="img">
            <el-input v-model="form.img" placeholder="请输入图片URL">
              <template #append>
                <el-button @click="previewImage">预览</el-button>
              </template>
            </el-input>
            <div class="image-preview-container">
              <el-image
                v-if="form.img"
                :src="form.img"
                style="width: 200px; height: 120px; margin-top: 10px;"
                fit="contain"
              />
              <span v-else class="preview-placeholder">图片预览</span>
            </div>
          </el-form-item>
          
          <el-form-item label="关联公告ID" prop="notice_id">
            <el-input-number v-model="form.notice_id" :min="1" :controls="false" placeholder="请输入关联公告ID" />
          </el-form-item>
          
          <el-form-item label="是否有效" prop="is_valid">
            <el-switch v-model="form.is_valid" active-text="有效" inactive-text="无效" />
          </el-form-item>
          
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="4"
              placeholder="请输入轮播图内容"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确认
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue'
  import { Plus, Search } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import axios from 'axios'
  
  // 数据状态
  const loading = ref(false)
  const carouselList = ref([])
  const searchQuery = ref('')
  
  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(5)
  
  // 表单相关
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const submitting = ref(false)
  const formRef = ref(null)
  const form = ref({
    id: null,
    img: '',
    title: '',
    content: '',
    notice_id: null,
    is_valid: true
  })
  
  // 表单验证规则
  const rules = {
    title: [
      { required: true, message: '请输入轮播图标题', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
    ],
    img: [
      { required: true, message: '请输入图片URL', trigger: 'blur' },
      { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
    ]
  }
  
  // 计算属性
  const filteredCarousels = computed(() => {
    if (!searchQuery.value) return carouselList.value
    
    return carouselList.value.filter(item => 
      item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  })
  
  const pagedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredCarousels.value.slice(start, end)
  })
  
  // 获取轮播图列表
  const fetchCarousels = async () => {
    try {
      loading.value = true
      const response = await axios.get('http://localhost:8080/hospital5_war/carousel/findAll')
      carouselList.value = response.data || []
    } catch (error) {
      console.error('获取轮播图列表失败:', error)
      ElMessage.error('获取轮播图列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 分页处理
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
  }
  
  // 打开新增对话框
  const openAddDialog = () => {
    isEdit.value = false
    form.value = {
      id: null,
      img: '',
      title: '',
      content: '',
      notice_id: null,
      is_valid: true
    }
    dialogVisible.value = true
  }
  
  // 打开编辑对话框
  const openEditDialog = (carousel) => {
    isEdit.value = true
    form.value = { 
      ...carousel,
      is_valid: carousel.is_valid !== null ? Boolean(carousel.is_valid) : true
    }
    dialogVisible.value = true
  }
  
  // 预览图片
  const previewImage = () => {
    if (form.value.img) {
      window.open(form.value.img, '_blank')
    }
  }
  
  // 提交表单
  const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 准备请求数据
    const requestData = {
      id: form.value.id || null,  // 确保null值正确处理
      img: form.value.img,
      title: form.value.title,
      content: form.value.content || null,
      notice_id: form.value.notice_id || null,
      is_valid: form.value.is_valid ? 1 : 0  // 转换为数据库期望的格式
    }
    
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }
    
    const apiUrl = isEdit.value 
      ? 'http://localhost:8080/hospital5_war/carousel/update' 
      : 'http://localhost:8080/hospital5_war/carousel/add'
    
    console.log('发送的数据:', JSON.stringify(requestData, null, 2)) // 调试日志
    
    const response = await axios.post(apiUrl, requestData, config)
    
    if (response.data.success) {
      ElMessage.success(response.data.message)
      dialogVisible.value = false
      fetchCarousels()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败详情:', {
      message: error.message,
      response: error.response?.data,
      config: error.config
    })
    
    let errorMsg = '操作失败，请稍后重试'
    if (error.response) {
      // 从后端获取更具体的错误信息
      errorMsg = error.response.data?.message || 
                 error.response.data?.error || 
                 `服务器错误: ${error.response.status}`
    }
    
    ElMessage.error(errorMsg)
  } finally {
    submitting.value = false
  }
}
  
  // 删除轮播图
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除该轮播图吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      const response = await axios.get(`http://localhost:8080/hospital5_war/carousel/delete?id=${id}`)
      
      if (response.data.success) {
        ElMessage.success(response.data.message)
        fetchCarousels()
      } else {
        ElMessage.error(response.data.message)
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error(error.response?.data?.message || '删除失败')
      }
    }
  }
  
  // 初始化加载数据
  onMounted(() => {
    fetchCarousels()
  })
  </script>
  
  <style scoped>
  .carousel-management {
    padding: 20px;
    background-color: #fff;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .filter-container {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
  }
  
  .search-input {
    width: 300px;
  }
  
  .image-preview-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .preview-placeholder {
    display: inline-block;
    width: 200px;
    height: 120px;
    margin-top: 10px;
    line-height: 120px;
    text-align: center;
    border: 1px dashed #dcdfe6;
    color: #909399;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>